<?php

declare(strict_types=1);

namespace App\Controller\authority;
use App\Controller\BaseController;
use App\Model\AuthRole;
use App\Service\authority\AuthRoleService;
use App\Service\CommicService;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\Di\Annotation\Inject;
use App\Model\User;
use App\Common\Response\SystemCode;
use App\Service\authority\UserService;
#[AutoController]
class UserController  extends BaseController
{

    #[Inject]
    private UserService $userService;
    #[Inject]
    private CommicService $commicService;
    #[Inject]
    private AuthRoleService $authRoleService;
    /**
     * 用户列表
     */
    public function Index(RequestInterface $request)
    {

        $data = $this->userService->search($request->query());

        return $this->response(SystemCode::SYSTEM_SUCCESS, '请求成功',$data);

    }
    /**
     * 用户详情
     */
    public function View(int $id,RequestInterface $request)
    {
        if(!empty($id)) {
            $userInfo = User::query()->select('id', 'username', 'real_name', 'roles_ids','status','sort','company_id','email','phone')->where('id', $id)->first();
            if (empty($userInfo)) {
                return $this->response(SystemCode::SYSTEM_ERROR, '用户不存在');
            }
            return $this->response(SystemCode::SYSTEM_SUCCESS, '请求成功', $userInfo);
        }
    }

    /**
     * 用户创建
     */
    public function Create(RequestInterface $request){

        $result = $this->userService->createOrUpdate($request->post());

        if($result['code'] == SystemCode::SYSTEM_SUCCESS){
            return $this->response(SystemCode::SYSTEM_SUCCESS, '创建成功');
        }else{
            return $this->response(SystemCode::SYSTEM_ERROR, $result['message']);

        }
    }

    /**
     * 用户删除
     */
    public function Delete(int $id,RequestInterface $request)
    {
        if(!empty($id)) {
            $userInfo = User::query()->where('id', $id)->first();
            if (empty($userInfo)) {
                return $this->response(SystemCode::SYSTEM_ERROR, '用户不存在');
            }
            $userInfo->deleted_at = date('Y-m-d H:i:s');
            $userInfo->save();
            return $this->response(SystemCode::SYSTEM_SUCCESS, '操作成功');
        }
    }
    /**
     * 用户更新
     */
    public function Update(int $id,RequestInterface $request){

        if(empty($id)){
            return $this->response(SystemCode::SYSTEM_ERROR, '错误请求');
        }else{
            $userInfo = User::query()->select('id', 'username', 'real_name', 'roles_ids','status','sort','company_id','email','phone')->where('id', $id)->first();

            if(empty($userInfo)){
                return $this->response(SystemCode::SYSTEM_ERROR, '用户不存在');
            }
            if($request->getMethod() == 'GET'){
                $userInfo->roles_ids = explode(",", $userInfo->roles_ids);
                return $this->response(SystemCode::SYSTEM_SUCCESS, '查询成功',$userInfo);

            }else{
                $result = $this->userService->createOrUpdate($request->post(),true,$userInfo);

                if($result['code'] == SystemCode::SYSTEM_SUCCESS){
                    return $this->response(SystemCode::SYSTEM_SUCCESS, '修改成功');
                }else{
                    return $this->response(SystemCode::SYSTEM_ERROR, $result['message']);

                }
            }
        }
    }
    /**
     * 用户登录
     */
    public function Login(RequestInterface $request, ResponseInterface $response)
    {
        $params             = $request->post();
        $userInfo           = $this->userService->checkUser($params['username'],$params['password']);
        if(empty($userInfo)){
            return $this->response(SystemCode::SYSTEM_ERROR_PASSWORD, '用户不存在或者密码错误');
        }
        $tokenInfo = $this->userService->generateToken($userInfo->username);
//        if(!empty($userInfo->access_token)){
//            $this->userService->delUser($userInfo->access_token);
//        }
        $userInfo->access_token = $tokenInfo['access_token'];
        $userInfo->save();
        $menuList = $this->commicService->getMenuList($userInfo);
        $appletInfo = $this->commicService->getAppletInfo($userInfo,0);
        $is_admin = 0;
        $is_statistical = 0;
        $is_check_user_order = 0;
        unset($userInfo->password);
        if(!empty($userInfo->roles_ids)){
            $roles_ids = explode(',',$userInfo->roles_ids);
            $rolesData = AuthRole::query()->whereIn('id',$roles_ids)->select(['id','is_admin','is_statistical'])->get()->toArray();
           if(!empty($rolesData)){
                foreach ($rolesData as $rolesDatum){
                    if(!empty($rolesDatum['is_admin'])){
                        $is_admin = $rolesDatum['is_admin'];
                    }
                    if(!empty($rolesDatum['is_statistical'])){
                        $is_statistical = $rolesDatum['is_statistical'];
                    }

                }
           }
        }

        //2023-12-14 判断用户是否有对应的对应的权限
        if($is_check_user_order == 0){
            if(in_array('delivery:checkUserOrder:check',$menuList['permissions'])){
                $is_check_user_order = 1;
            }
        }
        $returnRes = array();
        if(in_array('delivery:delivery:teamList',$menuList['permissions'])){
            $userData = User::query()->where('roles_ids','like','%57%')->where('id','!=', $userInfo['id'])->select(['id as value','real_name as label'])->get()->toArray();
            $returnData = [['value' => 1,'label' => '全部投放组员'],
                ['value' => $userInfo['id'],'label' => $userInfo['real_name']],
            ];
            $returnRes = array_merge($returnData,$userData);
        }

        $returnData   = [
            'token'       => $tokenInfo['access_token'],
            'is_admin'    => $is_admin,
            'is_statistical' => $is_statistical,
            'is_check_user_order'=> $is_check_user_order,
            'message'     => 'welcome',
            'expire_in'   => $tokenInfo['expire_in'],
            'menuList'    => $menuList['menuList'],
            'permissions' => $menuList['permissions'],
            'user'        => $userInfo,
            'applet'      => $appletInfo,
            'delivery'    => $returnRes
        ];

        $this->userService->setUser($tokenInfo['access_token'],$returnData);

        return $this->response(SystemCode::SYSTEM_SUCCESS, '登录成功',$returnData);
    }







    public function refreshPermissions(RequestInterface $request)
    {


       if(empty($request->getHeader('Mema-Token')[0])){
           return $this->response(SystemCode::SYSTEM_TOKEN_EXPIRE, 'token 过期');
       }else{
          $access_token =  $request->getHeader('Mema-Token')[0];
          $permission =   $this->userService->refreshPermissions($access_token);

       }
       if(empty($permission)){
           return $this->response(SystemCode::SYSTEM_TOKEN_EXPIRE, 'token 过期');
       }else{
           return $this->response(SystemCode::SYSTEM_SUCCESS, '请求成功',$permission);
       }
    }

    public function changePwd(RequestInterface $request)
    {
        $pwd       = $request->post('password');
        $pwdRepeat = $request->post('password_repeat');
        $oldPwd    = $request->post('old_password');
        if ($pwd != $pwdRepeat) {
            return $this->response(SystemCode::SYSTEM_ERROR, '两次密码输入不一致');
        }
        if(empty($request->getHeader('Mema-Token')[0])){
            return $this->response(SystemCode::SYSTEM_TOKEN_EXPIRE, 'token 过期');
        }else{
            $access_token =  $request->getHeader('Mema-Token')[0];
            $userInfo =  $this->userService->getUser($access_token);
        }
        if(empty($userInfo)){
            return $this->response(SystemCode::SYSTEM_TOKEN_EXPIRE, 'token 过期');
        }
        $userInfo = json_decode($userInfo,true);

        $user = User::find($userInfo['user']['id']);
        if ($user->password != md5($oldPwd)) {
            return $this->response(SystemCode::SYSTEM_ERROR, '旧密码不正确');
        }
        $user = User::query()->where('id',$userInfo['user']['id'])->select('id','username','access_token','real_name','roles_ids')->first();
        $user->password = md5($pwd);
        if ($user->save()) {
            return $this->response(SystemCode::SYSTEM_SUCCESS, '密码修改成功',$user);
        }
        return $this->response(SystemCode::SYSTEM_ERROR, '密码修改失败');
    }

    public function changeRealName(RequestInterface $request)
    {
        $realname       = $request->post('realname');
        if(empty($request->getHeader('Mema-Token')[0])){
            return $this->response(SystemCode::SYSTEM_TOKEN_EXPIRE, 'token 过期');
        }else{
            $access_token =  $request->getHeader('Mema-Token')[0];
            $userInfo =  $this->userService->getUser($access_token);
        }
        if(empty($userInfo)){
            return $this->response(SystemCode::SYSTEM_TOKEN_EXPIRE, 'token 过期');
        }
        $userInfo = json_decode($userInfo,true);

        $user = User::query()->where('id',$userInfo['user']['id'])->select('id','username','access_token','real_name','roles_ids')->first();
        $user->real_name =$realname;
        if ($user->save()) {
            return $this->response(SystemCode::SYSTEM_SUCCESS, '昵称修改成功',$user);
        }
        return $this->response(SystemCode::SYSTEM_ERROR, '昵称修改失败');
    }

}